package com.server.ioc;

import com.common.tools.CommonTool;
import com.server.annotation.RpcBean;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

/**
 * @author Zixiang Hu
 * @description
 * @create 2021-04-16-15:45
 */
@Slf4j
public class RpcIOC {
    private HashMap<Class, Object> instances;
    private String scanPackage;

    public RpcIOC(String scanPackage) {
        this.scanPackage = scanPackage;
        instances = new HashMap<>();
        loadClass();
    }

    private void loadClass() {
        try {
            Set<String> classes = CommonTool.getClasses(scanPackage);
            for (String clazz : classes) {
                addObj(clazz);
            }
        } catch (Exception e) {
            log.error("RpcIOC的loadClass方法发生异常，异常信息是：{}", e.getMessage());
        }
    }

    private void addObj(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class clazz = Class.forName(className);
        if (clazz.isAnnotationPresent(RpcBean.class)) {
            Object newInstance = clazz.newInstance();
            Class[] interfaces = clazz.getInterfaces();
            for (Class anInterface : interfaces) {
                instances.put(anInterface, newInstance);
            }
        }
    }

    public Object getBean(Class clazz) {
        return instances.get(clazz);
    }
}
